﻿using System.Diagnostics;
using Atha.Contracts;
using Atha.Extensions.Strings;
using IronPython.Hosting;
using Microsoft.Scripting;

namespace Atha.Languages.IronPython
{
	public sealed class PythonTestRunContext : ScriptTestRunContextBase
	{
		public PythonTestRunContext(string name, string script)
			: base(name, script)
		{
		}

		protected override void OnExecute(string script, ITestRunResultBuilder testRunResultBuilder)
		{
			try
			{
				var py = Python.CreateEngine();
				var pyScope = py.CreateScope();

				var executionCtx = new CamelCaseTestExecutionContext(testRunResultBuilder);

				pyScope.SetVariable("atha", executionCtx);

				py.Execute(script, pyScope);
			}
			catch (SyntaxErrorException syntaxErrorException)
			{
				Debug.WriteLine("Error on Ln {0}, Col {1}: {2}".FormatWith(syntaxErrorException.Line, syntaxErrorException.Column, syntaxErrorException.Message));

				testRunResultBuilder.AddResult(new SyntaxExceptionTestResult(syntaxErrorException.Line, syntaxErrorException.Column, syntaxErrorException));
			}
		}
	}
}